package com.app.sgd.plugin;

import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.ConnectException;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFamily;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class OpenOfficeConverter {
	// connect to an OpenOffice.org instance running on port 8100
	private OpenOfficeConnection connection = null;

	/**
	 * @param oHTMLText
	 * @param oOutputStream
	 */
	public void convertFromHTMLToPDF(String oHTMLText,
			OutputStream oOutputStream) {
		try {
			DocumentFormat inputDocumentFormat = new DocumentFormat("HTML",DocumentFamily.TEXT, "text/html", "html");
			inputDocumentFormat.setExportFilter(DocumentFamily.TEXT,"HTML 	(StarWriter)");
			DocumentFormat outputDocumentFormat = new DocumentFormat(
					"Portable	Document Format", DocumentFamily.TEXT,
					"application/pdf", "pdf");
			outputDocumentFormat.setExportFilter(DocumentFamily.TEXT,
					"writer_pdf_Export");
			DocumentConverter oDocumentConverter = new OpenOfficeDocumentConverter(connection);
			oDocumentConverter.convert(
					new ByteArrayInputStream(oHTMLText.getBytes()),
					inputDocumentFormat, oOutputStream, outputDocumentFormat);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 
	 */
	public void openConnection() {
		try {
			if (connection == null || !connection.isConnected())
				connection = new SocketOpenOfficeConnection(8100);
			connection.connect();
		} catch (ConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	public void openConnection(String host, int port) {
		try {
			if (connection == null || !connection.isConnected())
				connection = new SocketOpenOfficeConnection(host, port);
			connection.connect();
		} catch (ConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	public void closeConnection() {
		// close the connection
		try {
			if (connection != null && connection.isConnected())
				connection.disconnect();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}